<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\admin\model\course\Order;
use app\admin\model\finance\Recharge;
use app\admin\model\finance\Withdrawal;
use app\admin\model\shop\Goods;
use app\admin\model\store\Apply;
use app\admin\model\store\Category;
use app\admin\model\Third;
use app\common\controller\Api;
use app\common\model\Area;
use app\common\model\MoneyLog;
use app\common\model\order\PayLog;
use think\Db;
use think\Validate;

/**
 * 财务模块
 * @ApiWeigh (21)
 */
class Finance extends Api
{
    protected $noNeedRight = ['*'];

    /**
     * 获取钱包明细
     * @ApiMethod   (POST)
     * @ApiParams   (name="page", type="integer", required=true, description="页码")
     * @ApiParams   (name="type", type="integer", required=true, description="类型1余额2积分")
     * @ApiParams   (name="symbol", type="integer", required=true, description="1:收入；2：支出")
     * @ApiReturnParams   (name="id", type="integer", required=true, description="分类id")
     */
    public function getMoneyList()
    {
        $type = $this->request->post("type");
        $symbol = $this->request->post("symbol");
        $where = [
            "type" => $type,
        ];
        if($symbol){
            $where['symbol'] = $symbol;
        }
        $userMoneyLog = new MoneyLog();
        $list = $userMoneyLog->where("user_id", $this->auth->id)
            ->where($where)
            ->order("id", "desc")
            ->paginate();
        if(count($list) >0) {
            foreach ($list as $key=>$value) {
                $value["from_type_text"] = $userMoneyLog->getFromTypeItem($value["from_type"]);
            }
        }
        $this->success("查询成功", $list);
    }




    /**
     * 获取VIP信息
     *
     * @ApiMethod (POST)
     *
     */
    public function getVipData()
    {
        $vip_money = \config("site.vip_money");
        $res = [
            "vip_money" => $vip_money,
            "is_vip" => $this->auth->is_vip,
        ];
        $this->success("查询成功",$res);
    }


    /**
     * 购买VIP
     * @ApiMethod (POST)
     *
     */
    public function buyVip(){
        if($this->auth->is_vip){
            $this->error("您已经是VIP了，无需重复购买");
        }
        $vip_money = \config("site.vip_money");
//        $pay_from = $this->request->post("pay_from");
        $pay_from = "miniapp";
//        $pay_type = $this->request->post("pay_type");
        $pay_type = "wechat";
        if(!in_array($pay_from, ["miniapp", "app"])){
            $this->error("支付类型错误");
        }
        if(!in_array($pay_type, ["wechat", "alipay"])){
            $this->error("支付方式错误");
        }
        $payLog = new PayLog();
        $aliPay = "";
        $wechatPay = [];
        $order_sn = $payLog->getOrderSn(PayLog::SUPER_VIP);



        Db::startTrans();
        try {


            switch ($pay_type){
                case "wechat":
                    //微信支付
                    $params = [
                        'type'         => $pay_type,
                        'orderid' => $order_sn,
                        'title'        => "购买VIP",
                        'amount'       => $vip_money,
                        'method'       => $pay_from,
                        'notifyurl'    => $this->request->domain() . "/api/common/notify/type/" . $pay_type . "/from/" . $pay_from,
                        'returnurl'    => $this->request->domain(),
                    ];
                    if($pay_from == "miniapp"){
                        $openid = Third::where("user_id",$this->auth->id)->where("platform","wechatMiniApp")->value("openid");
                        if(!$openid){
                            exception("当前小程序用户没有小程序id,请联系管理员");
                        }
                        $params["openid"] = $openid;
                    }

                    $wechatPay =  Service::submitOrder($params);

                    $payLog->createPayLog($this->auth->getUser(), $order_sn, $vip_money, $pay_from, $pay_type, []);
                    break;
                case "alipay":
                    //支付宝支付
                    $params = [
                        'type'         => $pay_type,
                        'orderid' => $order_sn,
                        'title'        => "购买VIP",
                        'amount'       => $vip_money,
                        'method'       => $pay_from,
                        'notifyurl'    => $this->request->domain() . "/api/common/notify/type/" . $pay_type. "/from/" . $pay_from,
                        'returnurl'    => $this->request->domain(),
                    ];
                    $aliPay =  Service::submitOrder($params);
                    $payLog->createPayLog($this->auth->getUser(), $order_sn, $vip_money, $pay_from, $pay_type, []);
                    break;
            }
            $res = [
                "wechatPay" => $wechatPay,
                "aliPay" => $aliPay,
            ];
            Db::commit();
        }catch (\Exception $exception){
            Db::rollback();
            $this->error($exception->getMessage());

        }
        $this->success("下单成功", $res);
    }
    /**
     * 获取充值信息
     *
     * @ApiMethod (POST)
     *
     */
    public function getRechargeData()
    {

        $recharge_low_money = \app\common\model\User::getRechargeLowMoney($this->auth->getUser());

        $res = [
            "recharge_low_money" => $recharge_low_money
        ];
        $this->success("查询成功",$res);
    }

    /**
     * 充值
     * @ApiMethod   (POST)
     * @ApiParams   (name="money", type="float", required=true, description="充值金额")
     */
    public function rechargeMoney(){
        $money = $this->request->post("money");
//        $pay_from = $this->request->post("pay_from");
        $pay_from = "miniapp";
//        $pay_type = $this->request->post("pay_type");
        $pay_type = "wechat";
        if(!in_array($pay_from, ["miniapp", "app"])){
            $this->error("支付类型错误");
        }
        if(!in_array($pay_type, ["wechat", "alipay"])){
            $this->error("支付方式错误");
        }
        $payLog = new PayLog();
        $aliPay = "";
        $wechatPay = [];
        $order_sn = $payLog->getOrderSn(PayLog::RECHARGE_MONEY);
        $recharge_low_money = \app\common\model\User::getRechargeLowMoney($this->auth->getUser());
        if($money < $recharge_low_money){
            $this->error("最少充值".$recharge_low_money."元");
        }

        Db::startTrans();
        try {


            switch ($pay_type){
                case "wechat":
                    //微信支付
                    $params = [
                        'type'         => $pay_type,
                        'orderid' => $order_sn,
                        'title'        => "充值",
                        'amount'       => $money,
                        'method'       => $pay_from,
                        'notifyurl'    => $this->request->domain() . "/api/common/notify/type/" . $pay_type . "/from/" . $pay_from,
                        'returnurl'    => $this->request->domain(),
                    ];
                    if($pay_from == "miniapp"){
                        $openid = Third::where("user_id",$this->auth->id)->where("platform","wechatMiniApp")->value("openid");
                        if(!$openid){
                            exception("当前小程序用户没有小程序id,请联系管理员");
                        }
                        $params["openid"] = $openid;
                    }

                    $wechatPay =  Service::submitOrder($params);

                    $payLog->createPayLog($this->auth->getUser(), $order_sn, $money, $pay_from, $pay_type, []);
                    break;
                case "alipay":
                    //支付宝支付
                    $params = [
                        'type'         => $pay_type,
                        'orderid' => $order_sn,
                        'title'        => "购买VIP",
                        'amount'       => $money,
                        'method'       => $pay_from,
                        'notifyurl'    => $this->request->domain() . "/api/common/notify/type/" . $pay_type. "/from/" . $pay_from,
                        'returnurl'    => $this->request->domain(),
                    ];
                    $aliPay =  Service::submitOrder($params);
                    $payLog->createPayLog($this->auth->getUser(), $order_sn, $money, $pay_from, $pay_type, []);
                    break;
            }
            $res = [
                "wechatPay" => $wechatPay,
                "aliPay" => $aliPay,
            ];
            Db::commit();
        }catch (\Exception $exception){
            Db::rollback();
            $this->error($exception->getMessage());

        }
        $this->success("下单成功", $res);
    }
}
